package controller.classServlet;

import entity.ClassEntity;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.ClassService;
import service.impl.ClassServiceImpl;
import controller.student.StudentServlet;
import util.BaseResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/updateClass")
public class UpdateClassServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json;charset=UTF-8");
            BufferedReader reader = req.getReader();
            Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {
            });

            ClassEntity classEntity = new ClassEntity();
            classEntity.setId((String) body.get("classId"));
            classEntity.setSpecialtyId((String) body.get("specialtyId"));
            classEntity.setTeacherId((String) body.get("teacherId"));
            classEntity.setClassName((String) body.get("className"));
            classEntity.setClassCode((String) body.get("classCode"));

            ClassService classService = new ClassServiceImpl();
            classService.updateClassInfo(classEntity);

            resp.setContentType("application/json;charset=UTF-8");

            BaseResult<Void> result = BaseResult.success();
            // 序列化并写入响应
            String jsonResponse = objectMapper.writeValueAsString(result);
            resp.getWriter().write(jsonResponse);
        } catch (Exception e) {
            logger.error("修改班级信息错误", e);

            BaseResult<Void> errorResult = BaseResult.failed(500, "修改班级信息失败: " + e.getMessage());

            resp.setContentType("application/json;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            String jsonError = objectMapper.writeValueAsString(errorResult);
            resp.getWriter().write(jsonError);
        }
    }
}
